package com.zbest.zpay.shared.process;

import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

/**
 * 隐式传参帮助类.
 * 
 * @author hangdh
 * 
 */
public class ActionContext {

	private final Map<String, Object> param = new HashMap<String, Object>();

	private final Map<String, Object> request = new HashMap<String, Object>();
	
	private boolean end = false;

	private static final ThreadLocal<Stack<ActionContext>> CONTEXT = new ThreadLocal<Stack<ActionContext>>() {
		@Override
		protected Stack<ActionContext> initialValue() {
			return new Stack<ActionContext>();
		}
	};

	public void setParam(String key, Object value) {
		this.param.put(key, value);
	}

	public Object getParam(String key) {
		return this.param.get(key);
	}

	public static ActionContext getContext() {
		if (CONTEXT.get().size() <= 0) {
			return new ActionContext();
		} else {
			return CONTEXT.get().peek();
		}
	}

	public static void removeContext() {
		CONTEXT.get().pop();
		if (CONTEXT.get().size() <= 0) {
			CONTEXT.remove();
		}
	}

	public void clearParam() {
		this.param.clear();
	}

	public void setRequest(Map<String, Object> request) {
		if (request != null) {
		    this.request.clear();
			this.request.putAll(request);
			CONTEXT.get().push(this);
		}
	}

	public Map<String, Object> getRequest() {
		return CONTEXT.get().peek().request;
	}

	public Map<String, Object> getAllData() {
		ActionContext ac = CONTEXT.get().peek();

		Map<String, Object> map = new HashMap<String, Object>();
		map.putAll(ac.request);
		map.putAll(ac.param);
		return map;
	}

	protected ActionContext() {
	}

	public boolean isEnd() {
		return end;
	}

	public void setEnd(boolean end) {
		this.end = end;
	}

}